package cn.iocoder.yudao.module.ordering.service.record;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils;
import cn.iocoder.yudao.module.ordering.constant.Constants;
import cn.iocoder.yudao.module.ordering.controller.admin.record.vo.RecordPageReqVO;
import cn.iocoder.yudao.module.ordering.controller.admin.record.vo.RecordSaveReqVO;
import cn.iocoder.yudao.module.ordering.dal.dataobject.record.RecordDO;
import cn.iocoder.yudao.module.ordering.dal.mysql.record.RecordMapper;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.ordering.enums.ErrorCodeConstants.RECORD_NOT_EXISTS;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.USER_NOT_EXISTS;

/**
 * 餐品-订餐记录 Service 实现类
 *
 * @author 芋道源码
 */
@Service(value = "foodRecordService")
@Validated
public class RecordServiceImpl implements RecordService {

    @Resource
    private RecordMapper recordMapper;
    @Resource
    private AdminUserApi userApi;
    @Resource
    private DeptApi deptApi;
    @Override
    /**
     * 创建记录
     *
     * @param params 记录保存请求参数
     * @return 创建的记录的ID
     */
    public Long createRecord(RecordSaveReqVO params) {
        // 将参数对象转换为数据库实体
        RecordDO record = BeanUtils.toBean(params, RecordDO.class);

        // 根据用户id获取用户基本信息
        AdminUserRespDTO user = userApi.getUser(WebFrameworkUtils.getLoginUserId());
        // 如果用户不存在，则抛出异常
        if(user == null){
            throw exception(USER_NOT_EXISTS);
        }
        // 设置记录的用户ID和用户名
        record.setUserId(user.getId());
        record.setUserName(user.getNickname());

        // 如果用户有部门信息，则设置记录的部门ID和部门名称
        if(user.getDeptId() != null){
            DeptRespDTO dept = deptApi.getDept(user.getDeptId());
            record.setDeptId(dept.getId());
            record.setDeptName(dept.getName());
        }

        // 补充用户基本信息后插入数据库
        recordMapper.insert(record);
        // 返回创建的记录的ID
        return record.getId();
    }


    @Override
    public void updateRecord(RecordSaveReqVO updateReqVO) {
        // 校验存在
        validateRecordExists(updateReqVO.getId());
        // 更新
        RecordDO updateObj = BeanUtils.toBean(updateReqVO, RecordDO.class);
        recordMapper.updateById(updateObj);
    }

    @Override
    public void deleteRecord(Long id) {
        // 校验存在
        validateRecordExists(id);
        // 删除
        recordMapper.deleteById(id);
    }

    private void validateRecordExists(Long id) {
        if (recordMapper.selectById(id) == null) {
            throw exception(RECORD_NOT_EXISTS);
        }
    }

    @Override
    public RecordDO getRecord(Long id) {
        return recordMapper.selectById(id);
    }

    @Override
    public PageResult<RecordDO> getRecordPage(RecordPageReqVO pageReqVO) {
        return recordMapper.selectPage(pageReqVO);
    }

    @Override
    public Integer cancel(RecordDO recordDO) {
        return recordMapper.updateById(recordDO);
    }

    @Override
    public List<RecordDO> getTotalRecord(RecordDO pageReqVO) {
        // 1 查询订餐记录
        List<RecordDO> list = recordMapper.selectListCommon(pageReqVO);
        // 2 按照日期和餐品类型分组
        List<RecordDO> returnList = new ArrayList<>();
        list.stream().collect(Collectors.groupingBy(item -> item.getOrderDate() + item.getType()))
                .entrySet().stream().forEach(groupItem -> {
                    List<RecordDO> itemList = groupItem.getValue();
                    RecordDO recordDO = itemList.get(0);
                    recordDO.setPrice(itemList.stream()
                            .filter(item -> item != null)
                            .map(RecordDO::getPrice)
                            .reduce(BigDecimal.ZERO, BigDecimal::add));
                    recordDO.setItemNum(itemList.size());
                    recordDO.setItemList(itemList.stream()
                            .filter(item -> item != null && item.getName() != null)
                            .collect(Collectors.groupingBy(RecordDO::getName, Collectors.counting())));
                    returnList.add(recordDO);
                });
        // 3 返回查询的数据
        return returnList.stream()
                .sorted(Comparator.comparing(RecordDO::getType))
                .sorted(Comparator.comparing(RecordDO::getOrderDate).reversed())
                .collect(Collectors.toList());
    }

    @Override
    public Integer sendBatch(RecordDO recordDO) {
        return recordMapper.update(new LambdaUpdateWrapper<RecordDO>()
                .eq(RecordDO::getOrderDate, recordDO.getOrderDate())
                .eq(RecordDO::getType, recordDO.getType())
                .eq(RecordDO::getStatus, Constants.RECORD_STATUS_ORDERED)
                .set(RecordDO::getStatus, Constants.RECORD_STATUS_SEND)
        );
    }

}
